package xupt.com.bolg.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xupt.com.bolg.entity.User;
import xupt.com.bolg.repository.UserRepository;
import xupt.com.bolg.service.UserService;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserRepository userRepository;
    @Override
    public boolean deleteByID(Integer id) {
        userRepository.deleteById(id);
        return true;
    }

    @Override
    public boolean saveUser(User user) {
        user.setData(new Date());
        List<User> all = userRepository.findAll();
        if(!all.isEmpty()) {
            for (int i = 0; i < all.size(); i++) {
                if (all.get(i).getName().equals(user.getName())) {  //用户名存在
                    return false;
                }
            }
            user.setId(all.get(all.size()-1).getId() + 1);
            userRepository.save(user);
            return true;
        }
        userRepository.save(user);
        return true;
    }

    @Override
    public User findByName(String name) {
        List<User> all = userRepository.findAll();
        if(all.size()==0){
            return null;
        }
        for(int i=0;i<all.size();i++){
            if(all.get(i).getName().equals(name)){
               return all.get(i);
            }
        }
        return null;
    }

    @Override
    public User findByID(Integer id) {
        Optional<User> byId = userRepository.findById(id);
        if(byId==null){
            return null;
        }
        return byId.get();
    }

    @Override
    public boolean update(User user) {
        user.setData(new Date());
        List<User> all = userRepository.findAll();
        for(int i=0;i<all.size();i++){
            if(all.get(i).getId()==user.getId()){
              userRepository.save(user);
              return true;
            }
        }
        return false;
    }

    @Override
    public List<User> findAll() {
        return userRepository.findAll();
    }

    @Override
    public Integer count() {
        int size = userRepository.findAll().size();
        return size;
    }

    @Override
    public User findByEmail(String email) {
        if(email==null){
            return null;
        }
        List<User> all = userRepository.findAll();
        for(int i=0;i<all.size();i++){
            if (all.get(i).getEmail().equals(email)){
                return  all.get(i);
            }
        }
        return null;
    }
}
